<!-- FavoriteList.vue - 我的收藏 -->
<template>
  <div class="favorite-list-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon class="header-icon"><Star /></el-icon>
        <div>
          <h2 class="header-title">我的收藏</h2>
          <p class="header-subtitle">共 {{ favorites.length }} 件收藏商品</p>
        </div>
      </div>
      <el-button
        v-if="favorites.length > 0"
        type="danger"
        plain
        @click="handleBatchDelete"
        :disabled="selectedIds.length === 0"
      >
        批量删除 ({{ selectedIds.length }})
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="i in 8" :key="i">
          <el-skeleton :rows="5" animated class="loading-card" />
        </el-col>
      </el-row>
    </div>

    <!-- 空状态 -->
    <div v-else-if="favorites.length === 0" class="empty-state">
      <el-empty description="还没有收藏任何商品">
        <el-button type="primary" @click="$router.push('/gear/market')">
          去渔具市场逛逛
        </el-button>
      </el-empty>
    </div>

    <!-- 收藏列表 -->
    <div v-else class="favorites-grid">
      <div
        v-for="item in favorites"
        :key="item.favoriteId"
        class="favorite-card"
        @click="viewProduct(item.productId)"
      >
        <!-- 选择框 -->
        <el-checkbox
          v-model="item.isSelected"
          class="select-checkbox"
          @click.stop
        />

        <!-- 商品图片 -->
        <div class="product-image">
          <el-image :src="item.coverList && item.coverList[0] ? item.coverList[0] : ''" fit="cover">
            <template #loading>
              <div class="image-loading">
                <el-icon><Loading /></el-icon>
              </div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon><PictureFilled /></el-icon>
                <div style="font-size: 12px; margin-top: 5px;">
                  {{ item.coverList ? `原始: ${item.coverList}` : '无图片数据' }}
                </div>
              </div>
            </template>
          </el-image>

          <!-- 新旧程度标签 -->
          <el-tag
            :type="getOldLevelType(item.oldLevel)"
            size="small"
            class="level-tag"
          >
            {{ getOldLevelText(item.oldLevel) }}
          </el-tag>
        </div>

        <!-- 商品信息 -->
        <div class="product-info">
          <h3 class="product-name" :title="item.productName">
            {{ item.productName }}
          </h3>

          <div class="product-price">
            <span class="price">¥{{ item.price }}</span>
          </div>

          <div class="product-meta">
            <span class="collect-time">
              <el-icon><Clock /></el-icon>
              {{ formatDate(item.createTime) }}
            </span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="product-actions" @click.stop>
          <el-button
            type="danger"
            size="small"
            plain
            @click="handleRemoveFavorite(item)"
            icon="Delete"
          >
            取消收藏
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleAddToCart(item)"
            icon="ShoppingCart"
          >
            加入购物车
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { favoriteAPI, cartAPI } from '@/api'
import { useFavoriteStore } from '@/stores/favoriteStore'
import { useCartStore } from '@/stores/cartStore'
import {
  Star,
  Clock,
  Delete,
  ShoppingCart,
  Loading,
  PictureFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const favoriteStore = useFavoriteStore()

// 数据
const favorites = ref([])
const loading = ref(false)

// 选中的商品ID列表
const selectedIds = computed(() => {
  const selected = favorites.value.filter(item => item.isSelected).map(item => item.favoriteId)
  console.log('当前选中的商品ID:', selected)
  return selected
})

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    loading.value = true
    const response = await favoriteAPI.getMyFavorites()
    console.log('收藏列表响应:', response)

    if (response.code === 0) {
      const favoriteList = response.data || []
      console.log('收藏列表数据:', favoriteList)
      
      // 预处理coverList字段，确保是数组格式
      favorites.value = favoriteList.map(item => {
        console.log('收藏页面原始coverList:', item.coverList, '类型:', typeof item.coverList)
        const parsedCoverList = parseCoverList(item.coverList)
        console.log('收藏页面解析后coverList:', parsedCoverList)
        return {
          ...item,
          isSelected: false,
          coverList: parsedCoverList // 预处理coverList
        }
      })
      
      // 更新收藏store中的状态
      favoriteStore.updateFavoriteStatuses(favoriteList)
      
      console.log('处理后的收藏列表:', favorites.value)
    } else {
      console.error('获取收藏列表失败:', response.message)
      ElMessage.error('获取收藏列表失败')
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 取消收藏
const handleRemoveFavorite = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消收藏【${item.productName}】吗？`,
      '取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await favoriteStore.toggleFavorite(item.productId)
    if (result.success) {
      ElMessage.success('取消收藏成功')
      
      // 从列表中移除
      const index = favorites.value.findIndex(f => f.favoriteId === item.favoriteId)
      if (index > -1) {
        favorites.value.splice(index, 1)
      }
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  console.log('批量删除按钮被点击')
  console.log('选中的商品ID:', selectedIds.value)
  console.log('选中的商品数量:', selectedIds.value.length)
  
  if (selectedIds.value.length === 0) {
    return ElMessage.warning('请先选择要删除的商品')
  }

  try {
    await ElMessageBox.confirm(
      `确定要取消收藏选中的 ${selectedIds.value.length} 件商品吗？`,
      '批量取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    console.log('用户确认批量删除')
    
    // 批量删除
    const selectedItems = favorites.value.filter(item => item.isSelected)
    console.log('要删除的商品列表:', selectedItems)
    
    for (const item of selectedItems) {
      console.log(`正在删除商品: ${item.productName} (ID: ${item.productId})`)
      const result = await favoriteStore.toggleFavorite(item.productId)
      if (!result.success) {
        console.error(`删除商品 ${item.productName} 失败:`, result.message)
        ElMessage.error(`删除商品 ${item.productName} 失败`)
        return
      }
    }

    ElMessage.success('批量取消收藏成功')
    
    // 从列表中移除已删除的项
    favorites.value = favorites.value.filter(item => !item.isSelected)
    console.log('批量删除完成，剩余商品数量:', favorites.value.length)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 加入购物车
const handleAddToCart = async (item) => {
  try {
    // 检查商品是否已在购物车中
    const cartStore = useCartStore()
    if (cartStore.isInCart(item.productId)) {
      ElMessage.warning('该商品已在购物车中')
      return
    }
    
    // 二手商品数量固定为1
    await cartAPI.addCart(item.productId, 1)
    
    ElMessageBox.confirm(
      `已将【${item.productName}】添加到购物车`,
      '添加成功',
      {
        confirmButtonText: '去购物车',
        cancelButtonText: '继续浏览',
        type: 'success'
      }
    ).then(() => {
      router.push('/gear/cart')
    }).catch(() => {})
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  }
}

// 查看商品详情
const viewProduct = (productId) => {
  router.push(`/gear/product/${productId}`)
}

// 工具函数
const getFirstImage = (coverList) => {
  const parsedList = parseCoverList(coverList)
  return parsedList.length > 0 ? parsedList[0] : ''
}

/**
 * 安全解析 coverList 字段
 */
const parseCoverList = (coverList) => {
  // 如果已经是数组，直接返回
  if (Array.isArray(coverList)) {
    return coverList.filter(url => url && !url.startsWith('blob:'))
  }
  
  // 如果是字符串，尝试解析
  if (typeof coverList === 'string') {
    // 如果是空字符串，返回空数组
    if (!coverList.trim()) {
      return []
    }
    
    // 如果看起来像URL（以http开头），包装成数组
    if (coverList.startsWith('http')) {
      // 检查是否包含多个URL（没有分隔符的情况）
      // 修复正则表达式，更精确地匹配URL
      const urlPattern = /https?:\/\/[^,\s]+/g
      const urls = coverList.match(urlPattern)
      if (urls && urls.length > 0) {
        return urls.filter(url => url && !url.startsWith('blob:'))
      }
      return [coverList]
    }
    
    // 尝试解析JSON字符串
    try {
      const parsed = JSON.parse(coverList)
      
      // 处理嵌套的successUrls结构
      if (parsed && typeof parsed === 'object') {
        if (parsed.successUrls && Array.isArray(parsed.successUrls)) {
          return parsed.successUrls.filter(url => url && !url.startsWith('blob:'))
        }
        if (Array.isArray(parsed)) {
          return parsed.filter(url => url && !url.startsWith('blob:'))
        }
      }
      
      return Array.isArray(parsed) ? parsed.filter(url => url && !url.startsWith('blob:')) : []
    } catch (error) {
      return []
    }
  }
  
  // 其他情况返回空数组
  return []
}

const getOldLevelText = (level) => {
  const map = {
    1: '1成新', 2: '2成新', 3: '3成新', 4: '4成新', 5: '5成新',
    6: '6成新', 7: '7成新', 8: '8成新', 9: '9成新', 10: '全新'
  }
  return map[level] || '未知'
}

const getOldLevelType = (level) => {
  if (level >= 9) return 'success'
  if (level >= 7) return 'info'
  if (level >= 5) return 'warning'
  return 'danger'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now - date
    
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)
    
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 30) return `${days}天前`
    
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('格式化时间失败:', error)
    return ''
  }
}

onMounted(() => {
  fetchFavorites()
  
  // 监听订单创建事件，当有订单创建时刷新收藏列表
  const handleOrderCreated = (event) => {
    const { productId } = event.detail
    console.log('FavoriteList: 检测到订单创建，商品ID:', productId, '刷新收藏列表')
    
    // 立即从本地状态中移除该商品（如果存在）
    if (productId && favorites.value.length > 0) {
      const index = favorites.value.findIndex(fav => fav.productId === productId)
      if (index !== -1) {
        console.log('FavoriteList: 立即移除已售商品:', productId)
        favorites.value.splice(index, 1)
      }
    }
    
    // 刷新收藏列表（从后端获取最新数据）
    fetchFavorites()
  }
  
  window.addEventListener('orderCreated', handleOrderCreated)
  
  // 保存事件处理器引用，用于清理
  window._favoriteOrderCreatedHandler = handleOrderCreated
})

onUnmounted(() => {
  // 清理事件监听器
  if (window._favoriteOrderCreatedHandler) {
    window.removeEventListener('orderCreated', window._favoriteOrderCreatedHandler)
    delete window._favoriteOrderCreatedHandler
  }
})
</script>

<style scoped lang="scss">
$primary-color: #409eff;
$danger-color: #f56c6c;
$warning-color: #e6a23c;
$success-color: #67c23a;

.favorite-list-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.3);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .header-icon {
    font-size: 36px;
  }

  .header-title {
    font-size: 28px;
    margin: 0;
    font-weight: 600;
  }

  .header-subtitle {
    margin: 5px 0 0 0;
    font-size: 14px;
    opacity: 0.9;
  }
}

.loading-container {
  .loading-card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    height: 350px;
  }
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 80px 20px;
  text-align: center;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;

  .favorite-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);

      .product-actions {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .select-checkbox {
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 10;
      background: rgba(255, 255, 255, 0.95);
      padding: 5px;
      border-radius: 4px;
    }

    .product-image {
      width: 100%;
      height: 220px;
      position: relative;
      overflow: hidden;

      .el-image {
        width: 100%;
        height: 100%;
      }

      .image-loading,
      .image-error {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        color: #909399;
        font-size: 40px;
      }

      .level-tag {
        position: absolute;
        top: 10px;
        right: 10px;
        font-weight: 600;
      }
    }

    .product-info {
      padding: 15px;

      .product-name {
        font-size: 16px;
        color: #303133;
        margin: 0 0 10px 0;
        font-weight: 600;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        min-height: 44px;
      }

      .product-price {
        margin-bottom: 10px;

        .price {
          font-size: 22px;
          color: $danger-color;
          font-weight: 700;
        }
      }

      .product-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .collect-time {
          font-size: 12px;
          color: #909399;
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }

    .product-actions {
      padding: 0 15px 15px;
      display: flex;
      gap: 10px;
      opacity: 0;
      transform: translateY(10px);
      transition: all 0.3s;

      .el-button {
        flex: 1;
      }
    }
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;

    .favorite-card {
      .product-image {
        height: 150px;
      }

      .product-actions {
        opacity: 1;
        transform: translateY(0);
        flex-direction: column;
      }
    }
  }
}
</style>
